﻿using Coding4Fun.Lockscreen.Core.Models;
using Coding4Fun.Lockscreen.Core.Storage;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using Windows.Storage;

namespace Coding4Fun.Lockscreen.Mobile
{
    public partial class ImageSetPage : PhoneApplicationPage
    {
        List<string> downloadableItems;
        List<string> fileItems;

        public ImageSetPage()
        {
            InitializeComponent();
        }

        private async void btnSetStack_Click_1(object sender, EventArgs e)
        {
            var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication;
            if (!isProvider)
            {
                var op = await Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync();
                isProvider = op == Windows.Phone.System.UserProfile.LockScreenRequestResult.Granted;
            }

            if (isProvider)
            {
                downloadableItems = new List<string>();
                fileItems = new List<string>();

                foreach (var image in CentralBindingPoint.Instance.CurrentCategory.Images)
                {
                    if (Uri.IsWellFormedUriString(image.URL, UriKind.Absolute))
                    {
                        downloadableItems.Add(image.URL);
                    }
                }

                await LocalStorageHelper.ClearFolder("CurrentSet");

                try
                {
                    DownloadImages();

                    grdDownloading.Visibility = System.Windows.Visibility.Visible;
                    this.ApplicationBar.IsVisible = false;
                }
                catch
                {
                    MessageBox.Show("There seems to be a problem getting the wallpapers. Please try again later.",
                      "Download Wallpaper Sets", MessageBoxButton.OK);

                    grdDownloading.Visibility = System.Windows.Visibility.Collapsed;
                    this.ApplicationBar.IsVisible = true;
                }
            }
        }

        void DownloadImages()
        {
            WebClient client = new WebClient();
            string fullUrl = downloadableItems.First();

            string fileName = Path.GetFileName(fullUrl);

            client.OpenReadAsync(new Uri(fullUrl));
            client.OpenReadCompleted += async (sender, args) =>
                {
                    if (args.Error == null)
                    {
                        Debug.WriteLine("Downloaded " + fileName);
                        fileItems.Add(fileName);

                        bool written = await LocalStorageHelper.WriteData("CurrentSet", fileName, StreamToByteArray(args.Result));
                    }
                    else
                    {
                        Debug.WriteLine("Problem downloading the file.");
                    }

                    ProceedToNext();
                };
        }

        public void ProceedToNext()
        {
            downloadableItems.Remove(downloadableItems.First());
            if (downloadableItems.Count != 0)
                DownloadImages();
            else
            {
                grdDownloading.Visibility = System.Windows.Visibility.Collapsed;
                this.ApplicationBar.IsVisible = true;

                Coding4Fun.Toolkit.Storage.Serialize.Save<List<string>>("imagestack.xml", fileItems);

                LocalStorageHelper.CycleThroughImages();

                //ScheduledActionService.LaunchForTest("LockscreenChanger", TimeSpan.FromSeconds(5));
            }
        }

        public static byte[] StreamToByteArray(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        private void lstImages_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (lstImages.SelectedItem != null)
            {
                if (CentralBindingPoint.Instance.CustomCategories.Count > 0)
                {

                    ListPicker picker = new ListPicker()
                    {
                        Header = "Custom category name:",
                        ItemsSource = CentralBindingPoint.Instance.CustomCategories,
                        Margin = new Thickness(12, 42, 24, 18)
                    };

                    CustomMessageBox messageBox = new CustomMessageBox()
                    {
                        Caption = "Add To Custom Category",
                        Message = "Select a registered custom category to add this image to.",
                        Content = picker,
                        LeftButtonContent = "ok",
                        RightButtonContent = "cancel"
                    };

                    messageBox.Dismissing += (s, boxEventArgs) =>
                        {
                            if (picker.ListPickerMode == ListPickerMode.Expanded)
                            {
                                boxEventArgs.Cancel = true;
                            }
                        };

                    messageBox.Dismissed += (s2, e2) =>
                    {
                        switch (e2.Result)
                        {
                            case CustomMessageBoxResult.LeftButton:
                                {
                                    if (picker.SelectedItem != null)
                                    {

                                        Category category = (from c in CentralBindingPoint.Instance.CustomCategories
                                                             where c.Name == picker.SelectedItem.ToString()
                                                             select c).FirstOrDefault();

                                        if (category != null)
                                        {
                                            category.Images.Add((Coding4Fun.Lockscreen.Core.Models.Image)lstImages.SelectedItem);

                                            Coding4Fun.Toolkit.Storage.Serialize.Save<ObservableCollection<Category>>(
                                                "customcat.xml", CentralBindingPoint.Instance.CustomCategories);
                                        }

                                        lstImages.IsEnabled = true;
                                    }

                                    break;
                                }
                        }
                        lstImages.SelectedItem = null;
                    };

                    messageBox.Show();

                }
                else
                {
                    MessageBox.Show("Tapping on an image will prompt you to add it to a custom category" + Environment.NewLine +
                        "Seems like you don't have any custom categories yet.", "Add To Custom Category", MessageBoxButton.OK);
                    lstImages.SelectedItem = null;
                }
            }
        }
    }
}